<template>
  <div class="special-case-management">
    <!-- 功能切换 -->
    <div class="function-selector">
      <a-radio-group v-model:value="activeFunction" button-style="solid" size="large">
        <a-radio-button value="overview">总览</a-radio-button>
        <a-radio-button value="accident">意外死亡</a-radio-button>
        <a-radio-button value="disaster">自然灾害</a-radio-button>
        <a-radio-button value="war">战争伤亡</a-radio-button>
        <a-radio-button value="plague">瘟疫死亡</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 总览面板 -->
    <div v-if="activeFunction === 'overview'" class="overview-panel">
      <a-row :gutter="[24, 24]">
        <!-- 统计卡片 -->
        <a-col :xs="24" :sm="12" :lg="6" v-for="(type, key) in specialCaseTypes" :key="key">
          <div class="case-stat-card" :class="key">
            <div class="stat-icon">
              {{ type.icon }}
            </div>
            <div class="stat-content">
              <div class="stat-title">{{ type.name }}</div>
              <div class="stat-value">{{ getCaseCount(key) }}</div>
              <div class="stat-label">{{ type.unit }}</div>
            </div>
            <div class="stat-trend">
              <a-tag :color="type.trendColor" size="small">
                {{ type.trend }}
              </a-tag>
            </div>
          </div>
        </a-col>

        <!-- 特殊情况列表 -->
        <a-col :xs="24">
          <a-card title="特殊情况处理记录" class="cases-card">
            <template #extra>
              <a-space>
                <a-input-search v-model:value="searchKeyword" placeholder="搜索案例" style="width: 250px" @search="handleSearch" />
                <a-select v-model:value="severityFilter" placeholder="严重程度" style="width: 120px" @change="handleFilterChange">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option value="轻微">轻微</a-select-option>
                  <a-select-option value="中等">中等</a-select-option>
                  <a-select-option value="严重">严重</a-select-option>
                  <a-select-option value="特重大">特重大</a-select-option>
                </a-select>
                <a-button type="primary" @click="showAddCaseModal = true">
                  <PlusOutlined />
                  新增案例
                </a-button>
              </a-space>
            </template>

            <a-table :columns="caseColumns" :data-source="filteredSpecialCases" :loading="loading" :pagination="pagination" row-key="id" class="cases-table">
              <template #bodyCell="{ column, record }">
                <!-- 案例信息 -->
                <template v-if="column.key === 'caseInfo'">
                  <a-space direction="vertical" size="small">
                    <div class="case-name">{{ record.name }}</div>
                    <a-tag :color="getCaseTypeColor(record.caseType)" size="small">
                      {{ specialCaseTypes[record.caseType]?.name || record.caseType }}
                    </a-tag>
                  </a-space>
                </template>

                <!-- 严重程度 -->
                <template v-else-if="column.key === 'severity'">
                  <a-tag :color="getSeverityColor(record.severity)">
                    {{ record.severity }}
                  </a-tag>
                </template>

                <!-- 受影响情况 -->
                <template v-else-if="column.key === 'impact'">
                  <a-space direction="vertical" size="small">
                    <div>区域: {{ record.affectedArea }}</div>
                    <div>受害者: {{ record.estimatedVictims }}人</div>
                  </a-space>
                </template>

                <!-- 处理状态 -->
                <template v-else-if="column.key === 'status'">
                  <div class="status-info">
                    <a-tag :color="getStatusColor(record.investigationStatus)">
                      {{ record.investigationStatus }}
                    </a-tag>
                    <div class="response-action">{{ record.responseActions }}</div>
                  </div>
                </template>

                <!-- 操作 -->
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button type="link" size="small" @click="viewCaseDetail(record)"> 详情 </a-button>
                    <a-button type="link" size="small" @click="editCase(record)"> 编辑 </a-button>
                    <a-button type="link" size="small" @click="generateReport(record)"> 报告 </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 具体类型管理 -->
    <div v-else class="specific-type-management">
      <a-card :title="specialCaseTypes[activeFunction]?.name + '管理'" class="type-card">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="addSpecificCase">
              <PlusOutlined />
              新增{{ specialCaseTypes[activeFunction]?.name }}
            </a-button>
            <a-button @click="exportData">
              <ExportOutlined />
              导出数据
            </a-button>
            <a-button @click="generateAnalysis">
              <BarChartOutlined />
              生成分析
            </a-button>
          </a-space>
        </template>

        <!-- 类型专用界面 -->
        <div class="type-content">
          <!-- 意外死亡 -->
          <AccidentManagement v-if="activeFunction === 'accident'" />

          <!-- 自然灾害 -->
          <DisasterManagement v-if="activeFunction === 'disaster'" />

          <!-- 战争伤亡 -->
          <WarManagement v-if="activeFunction === 'war'" />

          <!-- 瘟疫死亡 -->
          <PlagueManagement v-if="activeFunction === 'plague'" />
        </div>
      </a-card>
    </div>

    <!-- 新增案例对话框 -->
    <a-modal v-model:open="showAddCaseModal" title="新增特殊情况" width="800px" :footer="null">
      <AddSpecialCaseForm @success="handleAddSuccess" @cancel="showAddCaseModal = false" />
    </a-modal>

    <!-- 案例详情对话框 -->
    <a-modal v-model:open="showDetailModal" title="案例详情" width="900px" :footer="null">
      <SpecialCaseDetail :case-data="selectedCase" @close="showDetailModal = false" @update="handleCaseUpdate" />
    </a-modal>

    <!-- 编辑对话框 -->
    <a-modal v-model:open="showEditModal" title="编辑案例" width="800px" :footer="null">
      <EditSpecialCaseForm :case-data="selectedCase" @success="handleEditSuccess" @cancel="showEditModal = false" />
    </a-modal>

    <!-- 分析报告对话框 -->
    <a-modal v-model:open="showAnalysisModal" title="分析报告" width="1000px" :footer="null">
      <AnalysisReport :case-type="activeFunction" :data="getAnalysisData()" @close="showAnalysisModal = false" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { PlusOutlined, ExportOutlined, BarChartOutlined } from '@ant-design/icons-vue'
import { useLifeDeathStore } from '@/stores/lifeDeath'
import AccidentManagement from './AccidentManagement.vue'
import DisasterManagement from './DisasterManagement.vue'
import WarManagement from './WarManagement.vue'
import PlagueManagement from './PlagueManagement.vue'
import AddSpecialCaseForm from './AddSpecialCaseForm.vue'
import SpecialCaseDetail from './SpecialCaseDetail.vue'
import EditSpecialCaseForm from './EditSpecialCaseForm.vue'
import AnalysisReport from './AnalysisReport.vue'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeFunction = ref('overview')
const searchKeyword = ref('')
const severityFilter = ref('all')
const showAddCaseModal = ref(false)
const showDetailModal = ref(false)
const showEditModal = ref(false)
const showAnalysisModal = ref(false)
const selectedCase = ref(null)

// 特殊情况类型定义
const specialCaseTypes = ref({
  accident: {
    name: '意外死亡',
    icon: '⚠️',
    unit: '起事故',
    trend: '本月-5%',
    trendColor: 'green'
  },
  disaster: {
    name: '自然灾害',
    icon: '🌪️',
    unit: '次灾害',
    trend: '本月+12%',
    trendColor: 'red'
  },
  war: {
    name: '战争伤亡',
    icon: '⚔️',
    unit: '次冲突',
    trend: '本月+3%',
    trendColor: 'orange'
  },
  plague: {
    name: '瘟疫死亡',
    icon: '🦠',
    unit: '次疫情',
    trend: '本月-8%',
    trendColor: 'green'
  }
})

// 表格列定义
const caseColumns = [
  {
    title: '案例信息',
    key: 'caseInfo',
    width: 200
  },
  {
    title: '严重程度',
    key: 'severity',
    width: 100
  },
  {
    title: '受影响情况',
    key: 'impact',
    width: 200
  },
  {
    title: '处理状态',
    key: 'status',
    width: 200
  },
  {
    title: '发生时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD')
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 计算属性
const loading = computed(() => lifeDeathStore.loading)

const filteredSpecialCases = computed(() => {
  let cases = lifeDeathStore.filteredSpecialCases

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    cases = cases.filter((caseItem) => caseItem.name.toLowerCase().includes(keyword) || caseItem.affectedArea.toLowerCase().includes(keyword) || caseItem.caseType.toLowerCase().includes(keyword))
  }

  if (severityFilter.value !== 'all') {
    cases = cases.filter((caseItem) => caseItem.severity === severityFilter.value)
  }

  pagination.value.total = cases.length
  return cases
})

// 方法
const getCaseCount = (type) => {
  return lifeDeathStore.specialCases.filter((caseItem) => caseItem.caseType === type).length
}

const getCaseTypeColor = (type) => {
  const colors = {
    accident: 'orange',
    disaster: 'red',
    war: 'volcano',
    plague: 'purple'
  }
  return colors[type] || 'default'
}

const getSeverityColor = (severity) => {
  const colors = {
    轻微: 'green',
    中等: 'orange',
    严重: 'red',
    特重大: 'volcano'
  }
  return colors[severity] || 'default'
}

const getStatusColor = (status) => {
  const colors = {
    进行中: 'processing',
    已完成: 'success',
    待审核: 'warning'
  }
  return colors[status] || 'default'
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleFilterChange = () => {
  // 过滤逻辑已在computed中处理
}

const viewCaseDetail = (caseData) => {
  selectedCase.value = caseData
  showDetailModal.value = true
}

const editCase = (caseData) => {
  selectedCase.value = caseData
  showEditModal.value = true
}

const generateReport = (caseData) => {
  message.success(`正在生成 ${caseData.name} 的报告`)
}

const addSpecificCase = () => {
  showAddCaseModal.value = true
}

const exportData = () => {
  const cases = filteredSpecialCases.value
  const csvContent = [
    ['案例名称', '类型', '严重程度', '受影响区域', '受害者人数', '处理状态', '发生时间'].join(','),
    ...cases.map((c) => [c.name, specialCaseTypes.value[c.caseType]?.name || c.caseType, c.severity, c.affectedArea, c.estimatedVictims, c.investigationStatus, dayjs(c.createdAt).format('YYYY-MM-DD')].join(','))
  ].join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `特殊情况_${activeFunction.value}_${dayjs().format('YYYY-MM-DD')}.csv`
  link.click()

  message.success('数据导出成功')
}

const generateAnalysis = () => {
  showAnalysisModal.value = true
}

const getAnalysisData = () => {
  return lifeDeathStore.specialCases.filter((c) => c.caseType === activeFunction.value)
}

const handleAddSuccess = () => {
  showAddCaseModal.value = false
  message.success('特殊情况添加成功')
}

const handleCaseUpdate = () => {
  showDetailModal.value = false
  message.success('案例更新成功')
}

const handleEditSuccess = () => {
  showEditModal.value = false
  message.success('案例编辑成功')
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.special-case-management {
  .function-selector {
    margin-bottom: 24px;
    text-align: center;
  }

  .overview-panel {
    .case-stat-card {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      gap: 16px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
      backdrop-filter: blur(10px);
      transition: all 0.3s ease;
      position: relative;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
        background: rgba(255, 255, 255, 0.08);
      }

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        background: rgba(255, 255, 255, 0.1);
        color: #ffffff;
      }

      .stat-content {
        flex: 1;

        .stat-title {
          font-size: 14px;
          color: rgba(255, 255, 255, 0.85);
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
          color: #ffffff;
        }

        .stat-label {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.65);
        }
      }

      .stat-trend {
        position: absolute;
        top: 12px;
        right: 12px;
      }

      &.accident {
        border-left: 4px solid #faad14;

        .stat-icon {
          background: rgba(250, 173, 20, 0.2);
          color: #faad14;
        }
      }

      &.disaster {
        border-left: 4px solid #ff4d4f;

        .stat-icon {
          background: rgba(255, 77, 79, 0.2);
          color: #ff4d4f;
        }
      }

      &.war {
        border-left: 4px solid #722ed1;

        .stat-icon {
          background: rgba(114, 46, 209, 0.2);
          color: #722ed1;
        }
      }

      &.plague {
        border-left: 4px solid #13c2c2;

        .stat-icon {
          background: rgba(19, 194, 194, 0.2);
          color: #13c2c2;
        }
      }
    }

    .cases-card {
      margin-top: 24px;

      .cases-table {
        .case-name {
          font-weight: 500;
          color: #1890ff;
        }

        .status-info {
          .response-action {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.65);
            margin-top: 4px;
          }
        }
      }
    }
  }

  .specific-type-management {
    .type-card {
      min-height: 600px;

      .type-content {
        padding: 16px 0;
      }
    }
  }
}
</style>
